package com.zkadmin.controller;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Button;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Window;

import com.zkadmin.entity.SysUser;
import com.zkadmin.renderer.SysUserListRenderer;
import com.zkadmin.service.SysRoleService;
import com.zkadmin.service.SysUserService;
import com.zkadmin.util.AdminConstants;
import com.zkadmin.util.AdminWebUtils;
import com.zkadmin.util.PagingWrap;

@SuppressWarnings("serial")
public class UserListCtrl extends BaseCtrl<Window> {
	Logger logger = LoggerFactory.getLogger(UserListCtrl.class);

	@WireVariable
	private SysUserService sysUserService;

	@WireVariable
	private SysRoleService sysRoleService;

	@Wire
	private Button createUserBtn;

	@Wire
	private Listbox userLst;

	@Wire
	private Paging userPg;

	@Override
	protected void init(Window win) {
		if (!SecurityUtils.getSubject().hasRole(AdminConstants.ROLE_ADMIN)) {
			createUserBtn.setDisabled(!SecurityUtils.getSubject().isPermitted("sys:user:create"));
		}

		userLst.setItemRenderer(new SysUserListRenderer(win, this, sysUserService));
		refreshData();
	}

	public void refreshData() {
		new PagingWrap<SysUser>(sysUserService, userLst, userPg).paging();
	}

	@Listen("onClick = #createUserBtn")
	public void showCreateUserModal(Event e) {
		Window window = (Window) Executions.createComponents(AdminWebUtils.getZulPagePath("admin/create_user_dialog.zul"), null, null);
		window.addEventListener(AdminConstants.EVENT_ONREFRESH, new EventListener<Event>() {
			@Override
			public void onEvent(Event event) throws Exception {
				refreshData();
			}
		});
		AdminWebUtils.eventAddCaption(window, e);
		window.doModal();
	}

}
